package com.dc.dbus.netty.node;

import com.dc.dbus.session.register.ZookeeperServiceRegister;
import com.dc.dbus.transport.commons.ServerAddress;
import com.dc.dbus.transport.commons.ServiceChangeListener;
import org.apache.zookeeper.KeeperException;

import java.io.IOException;

public class ZookeeperServiceRegisterNodeRouter extends ZookeeperServiceRegister {

    public ZookeeperServiceRegisterNodeRouter(
            String zkHostPort, int sessionTimeout,
            ServerAddress serverAddress, ServiceChangeListener listener) throws IOException {
        super(zkHostPort, sessionTimeout, serverAddress, listener);
    }

    protected synchronized String _registerService(String serviceName, String[] routers, String[] serviceHosts, int[] servicePorts) {

        String nodePath = super._registerService(serviceName, routers, serviceHosts, servicePorts);
        String nodeName = nodePath.substring(nodePath.lastIndexOf("/")+1);

        resetTheRouterToNodeName(nodePath, nodeName, serviceHosts, servicePorts);

        return nodePath;
    }

    protected void resetTheRouterToNodeName(String nodePath, String nodeName, String[] serviceHosts, int[] servicePorts) {

        StringBuilder serviceId = new StringBuilder(nodeName);
        serviceId.append(";");
        for (int i=0; ; ) {
            serviceId.append(serviceHosts[i]).append(":").append(servicePorts[i]);

            i++;
            if (i == serviceHosts.length) {
                break;
            } else {
                serviceId.append(",");
            }
        }

        try {
            zk.setData(nodePath, serviceId.toString().getBytes(), -1);
        } catch (KeeperException e) {
            if (e.code() == KeeperException.Code.CONNECTIONLOSS) {
                throw new RuntimeException("can't link to zookeeper", e);
            } else {
                throw new RuntimeException(e);
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
